package com.sunfeng.elasticsearch.elastic.term;

import com.sunfeng.elasticsearch.utils.ClientUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/5/6  17:27
 */
public class MatchQuery {
    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = null;
        try {
            client = ClientUtils.getInstance();
            matchQuery(client);
        } finally {
            assert client != null;
            client.close();
        }
    }

    private static void matchQuery(RestHighLevelClient client) throws IOException {
        SearchRequest searchRequest = new SearchRequest().indices("kibana_sample_data_logs");

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
      /* MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("message", "firefox chrome");
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("message", "firefox chrome").operator(Operator.OR);
        */
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("message", "firefox chrome").minimumShouldMatch("1").operator(Operator.OR);

        sourceBuilder.query(matchQueryBuilder);
        searchRequest.source(sourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getScore());
            System.out.println(hit.getSourceAsMap());
        }
    }
}
